package com.hex.es.component;

import com.google.common.collect.Maps;
import com.hex.es.annotation.EsBuildParamTypeInfo;
import com.hex.es.service.ExecutionLinkAfterInterface;
import com.hex.es.service.ExecutionLinkControllerInterface;
import com.hex.es.service.ParamBuildInterface;
import com.hex.es.service.ParamTypeCheckInterface;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description: 默认执行链路控制器
 * @author: Hex
 * @date: 2019/11/20 16:29
 */
@Slf4j
public class DefaultExecutionLinkController implements ExecutionLinkControllerInterface {

    private static final Map<Class,List<ParamBuildInterface>> BEAN_MAP = Maps.newConcurrentMap();

    @Resource
    private ExecutionLinkAfterInterface afterInterface;

    @Override
    public void paramBuild(Class<? extends ParamTypeCheckInterface> className, Object key, Object value, BoolQueryBuilder boolQueryBuilder, NativeSearchQueryBuilder searchQueryBuilder, EsBuildParamTypeInfo esBuildParamTypeInfo) {
        List<ParamBuildInterface> buildInterfaceList = BEAN_MAP.get(className);
        for (ParamBuildInterface paramBuildInterface : buildInterfaceList) {
            paramBuildInterface.paramBuild(key,value,boolQueryBuilder,searchQueryBuilder,esBuildParamTypeInfo);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ParamTypeCheckInterface> beansOfType = applicationContext.getBeansOfType(ParamTypeCheckInterface.class);
        beansOfType.forEach((key,value) -> {
            Map<Class, List<Class<? extends ParamBuildInterface>>> build = value.build();
            build.forEach((classKey,listValue) -> {
                List<ParamBuildInterface> buildInterfaceList = new ArrayList<>();
                listValue.forEach(x -> {
                    ParamBuildInterface bean = applicationContext.getBean(x);
                    buildInterfaceList.add(bean);
                });
                BEAN_MAP.put(classKey,buildInterfaceList);
            });
        });
        afterInterface.afterHandler(BEAN_MAP);
    }
}
